'use client';

import { Trip, User, Activity } from '@prisma/client';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import Link from 'next/link';
import { useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { SaveTripButton } from './SaveTripButton';
import type { TripWithDetails } from '@/app/types';

interface PopularTripCardProps {
  trip: TripWithDetails;
  initialSaved?: boolean;
}

export function PopularTripCard({ trip, initialSaved }: PopularTripCardProps) {
  const { data: session } = useSession();
  const router = useRouter();
  const [isSaving, setIsSaving] = useState(false);
  const [isSaved, setIsSaved] = useState(
    trip.savedBy.some(user => user.id === session?.user?.id)
  );

  const handleSave = async () => {
    if (!session) {
      router.push('/login');
      return;
    }

    setIsSaving(true);
    try {
      const response = await fetch(`/api/trips/${trip.id}/save`, {
        method: isSaved ? 'DELETE' : 'POST',
      });

      if (!response.ok) throw new Error('保存失败');
      setIsSaved(!isSaved);
    } catch (error) {
      console.error('Save error:', error);
    } finally {
      setIsSaving(false);
    }
  };

  const handleCopy = async () => {
    if (!session) {
      router.push('/login');
      return;
    }

    try {
      const response = await fetch(`/api/trips/${trip.id}/copy`, {
        method: 'POST',
      });

      if (!response.ok) throw new Error('复制失败');
      
      const data = await response.json();
      router.push(`/trips/${data.id}`);
      router.refresh();
    } catch (error) {
      console.error('Copy error:', error);
    }
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
      {trip.imageUrl && (
        <div className="aspect-w-16 aspect-h-9">
          <img
            src={trip.imageUrl}
            alt={trip.title}
            className="object-cover w-full h-48"
          />
        </div>
      )}
      <div className="p-6">
        <div className="flex items-start gap-4">
          <h3 className="text-lg font-semibold text-gray-900 flex-1 min-w-0">
            <Link href={`/trips/${trip.id}`} className="hover:text-blue-600 transition-colors">
              <span className="line-clamp-2">{trip.title}</span>
            </Link>
          </h3>
          <div className="flex items-start gap-2 flex-shrink-0">
            <SaveTripButton tripId={trip.id} initialSaved={initialSaved} />
            <button
              onClick={handleCopy}
              className="p-2 rounded-full text-gray-400 hover:text-blue-600 hover:bg-blue-50 transition-colors"
              title="复制到我的行程"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
              </svg>
            </button>
          </div>
        </div>

        {trip.description && (
          <p className="mt-2 text-sm text-gray-600 line-clamp-2">
            {trip.description}
          </p>
        )}

        <div className="mt-4 space-y-2">
          <div className="flex items-center text-gray-600">
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
            <span className="text-sm">
              {format(trip.startDate, 'MM月dd日', { locale: zhCN })} - {format(trip.endDate, 'MM月dd日', { locale: zhCN })}
            </span>
          </div>
          
          <div className="flex items-center justify-between text-gray-600">
            <div className="flex items-center">
              <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
              </svg>
              <span className="text-sm">{trip._count.activities} 个活动</span>
            </div>
            <div className="flex items-center">
              <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
              </svg>
              <span className="text-sm">{trip._count.savedBy} 人收藏</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
} 